# -*- coding: utf-8 -*-

import logging

from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class ProducePlan(models.Model):
    _name = 'buliao.produce.plan'

    name = fields.Char(u'计划号', required=True, index=True, readonly=True, default=lambda self: u'新建', copy=False)
    note = fields.Char(u'备注')
    state = fields.Selection([
        ('draft', u'未开始生产'),
        ('running', u'生产中'),
        ('done', u'生产完毕')
        ], string=u'计划单状态', readonly=True, copy=False, index=True, default='draft', compute='_compute_state')
    plan_date = fields.Datetime(
        string=u'创建时间', required=True, readonly=True, default=fields.Datetime.now, copy=False,
        states={'draft': [('readonly', False)]}
    )
    done_date = fields.Datetime(string=u'完成时间', readonly=True, copy=False)
    so_ids = fields.One2many('sale.order', 'plan_id', u'销售订单', readonly=True, states={'draft': [('readonly', False)]})
    partner_id = fields.Many2one(
        'res.partner', string=u'客户', readonly=True, required=True, index=True)
    user_id = fields.Many2one('res.users', string=u'制单员', index=True, track_visibility='onchange',
                              default=lambda self: self.env.user)

    @api.one
    @api.depends('so_ids.state')
    def _compute_state(self):
        if any(so.produce_state == 'running' for so in self.so_ids):
            self.state = 'running'
        elif any(so.produce_state == 'draft' for so in self.so_ids):
            self.state = 'draft'
        else:
            self.state = 'done'

    @api.model
    def create(self, vals):
        if vals.get('name', u'新建') == u'新建':
            if 'company_id' in vals:
                vals['name'] = self.env['ir.sequence'].with_context(
                    force_company=vals['company_id']).next_by_code('buliao.produce.plan') or u'新建'
            else:
                vals['name'] = self.env['ir.sequence'].next_by_code('buliao.produce.plan') or u'新建'
        result = super(ProducePlan, self).create(vals)
        return result




